<?php
/*
 * @Description:
 * @Version: 2.0
 * @Autor: wangyuqiang
 * @Date: 2021-01-25 10:06:53
 * @LastEditors: wangyuqiang
 * @LastEditTime: 2021-01-25 10:07:04
 */

namespace App\Http\Middleware;

use Closure;

class EnableCrossRequestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '*';

        if (isset($request->server()["HTTP_ORIGIN"])) {
            $httpOrigin = $request->server()["HTTP_ORIGIN"];
        } else {
            $httpOrigin = "*";
        }

        $allow_origin = [
            $httpOrigin,//允许访问
        ];
        if (in_array($origin, $allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept,token, Authorization, X-XSRF-TOKEN, X-Requested-With, X-TOKEN');
            $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE,OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
        }

        if ($request->getMethod() == "OPTIONS") {
            $header["Access-Control-Allow-Origin"] = $origin;
            $header["Access-Control-Allow-Headers"] = 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization,token, X-XSRF-TOKEN, X-Requested-With, X-TOKEN';
            $header["Access-Control-Expose-Headers"] = 'Authorization, authenticated';
            $header['Access-Control-Allow-Methods']= 'GET, POST, PATCH, PUT, DELETE,OPTIONS';
            $header["Access-Control-Allow-Credentials"] = 'true';
            return \Response::make('ok', 204, $header);
        }

        return $response;
    }
}
